<template>
  <div class="order-list">
    <h1>订单列表</h1>

    <!-- 订单表格 -->
    <table class="order-table">
      <thead>
        <tr>
          <th>订单号</th>
          <th>产品名称</th>
          <th>单价</th>
          <th>数量</th>
          <th>总金额</th>
          <th>订单日期</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- 遍历 orders 数组并显示每个订单的信息 -->
        <tr v-for="(order, index) in orders" :key="order.id">
          <td>{{ order.id }}</td>
          <td>{{ order.productName }}</td>
          <td>
            <input v-if="order.isEditing" v-model="order.price" type="number" step="0.01"/>
            <span v-else>{{ formatCurrency(order.price) }}</span>
          </td>
          <td>
            <input v-if="order.isEditing" v-model="order.quantity" type="number" min="1"/>
            <span v-else>{{ order.quantity }}</span>
          </td>
          <td>{{ formatCurrency(order.price * order.quantity) }}</td>
          <td>{{ formatDate(order.orderDate) }}</td>
          <td>
            <!-- 操作按钮: 删除和修改订单 -->
            <button @click="deleteOrder(order.id)">删除</button>
            <button @click="toggleEdit(order.id)">
              {{ order.isEditing ? '保存' : '修改' }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      orders: [], // 订单数据
      loading: false, // 加载状态
    };
  },
  created() {
    this.fetchOrders(); // 获取订单数据
  },
  methods: {
    // 模拟请求后端获取订单数据
    async fetchOrders() {
      this.loading = true;
      try {
        // 使用 axios 发起 GET 请求
        const response = await axios.get('http://localhost:8080/api/order/getAllOrders');

        // 获取数据并添加 isEditing 字段
        this.orders = response.data.map(order => ({
          ...order,
          isEditing: false // 添加 isEditing 字段，初始值为 false
        }));
      } catch (error) {
        console.error('获取订单数据失败:', error);
      } finally {
        this.loading = false;
      }
    },
    // 格式化日期
    formatDate(dateString) {
      const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' };
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', options); // 使用本地时间格式
    },
    // 格式化货币（美金）
    formatCurrency(value) {
      if (value === null || value === undefined) return '$0.00';
      return `$${value.toFixed(2)}`;
    },
    // 删除订单
    async deleteOrder(orderId) {
      const confirmed = confirm('确定要删除这个订单吗？');
      console.log(typeof(orderId));
      if (confirmed) {
        try {
          // 发送请求删除订单
          const response = await fetch(`http://localhost:8080/api/order/deleteOrder?id=${orderId}`, {
            method: 'DELETE', // 使用 DELETE 方法
            headers: {
              'Content-Type': 'application/json', // 设置请求头
            },
          });

          // 检查删除请求是否成功
          if (!response.ok) {
            throw new Error('删除失败');
          }

          // 订单删除成功后，从订单列表中移除该订单
          this.orders = this.orders.filter(order => order.id !== orderId);
          alert(`订单 ${orderId} 已删除`);
        } catch (error) {
          alert(`订单 ${orderId} 删除失败`)
          console.error('删除订单失败:', error);
        }
      }
    },
     // 切换编辑状态或保存订单
     async toggleEdit(orderId) {
      const order = this.orders.find(order => order.id === orderId);
      if (order.isEditing) {
        // 保存修改，向后端发送 PUT 请求
        try {
          const updatedOrder = {
            id: order.id,
            productName: order.productName,
            price: order.price,
            quantity: order.quantity,
            orderDate: order.orderDate,
          };
          const response = await axios.put(`http://localhost:8080/api/order/updateOrder?orderId=${orderId}`, updatedOrder);
          if (response.status === 200) {
            alert(`订单 ${orderId} 更新成功`);
          } else {
            throw new Error('更新失败');
          }
        } catch (error) {
          alert(`订单 ${orderId} 更新失败`);
          console.error('更新订单失败:', error);
        }
      }
      // 切换编辑状态
      order.isEditing = !order.isEditing;
    },
  },
};
</script>

<style scoped>
.order-list {
  padding: 20px;
}

h1 {
  font-size: 2em;
  margin-bottom: 20px;
}

.order-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.order-table th,
.order-table td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: left;
}

.order-table th {
  background-color: #f4f4f4;
}

button {
  padding: 5px 10px;
  margin: 0 5px;
  cursor: pointer;
}

.loading {
  font-size: 1.2em;
  color: #888;
}

input {
  width: 100px;
  padding: 5px;
  margin: 5px;
}
</style>
